<?php
/**
 ** added by lss@2017/07/21
 ** 修改原先emptyController下的定时到crontab下
**/
set_time_limit(0);
date_default_timezone_set("PRC");
require 'db_config.php';
//1.连接数据库->pdo方式
$db_pdo_link = pdo_write_read_link();

if(!$db_pdo_link)
{
	die('pdo connection failed!');
}

//2.定义远程api_url 和 彩种信息

$baseUrl = 'http://c.apiplus.net/newly.do?token=E0C5726B8E45A086&format=json&rows=3&code=';

$urlArr = array(
	34 => 'ahk3',    //安徽快3
	20 => 'bjpk10',  //北京赛车pk10
	1 => 'cqssc',	 //重庆时时彩
	21 => 'gdklsf',	 //广州快乐十分
	23 => 'bjkl8',   //快乐8
	3 => 'tjssc',    //天津时时彩
	18 => 'cqklsf',  //重庆农场
	22 => 'jsk3',    //江苏快3
	24 => 'shssl',   //上海时时乐
	67 => 'qxc',     //七星彩
	66 => 'mlaft',  //幸运飞艇
	35 => 'hk6',    //香港六合彩
	9 => 'fc3d',    //福彩3D
	6 => 'gd11x5',  //广东11选5
	7 => 'sd11x5',  //山东11选5
	16 => 'jx11x5', //江西11选5
	69 => 'tjklsf', //天津快乐十分  
	10 => 'pl3'     //排列三           33
);   


foreach ( $urlArr as $k=>$v )
{
	$ret = fopen_url($baseUrl.$v, '');
	$json = json_decode($ret,true);

	
	for($i=0;$i<count($json['data']);$i++)
	{
		$except = $json['data'][$i]['expect'];
		$open_time = $json['data'][$i]['opentimestamp'];
		$time_detail = $json['data'][$i]['opentime'];
		$codes = $json['data'][$i]['opencode'];
		
		
		$countCheck_res = $db_pdo_link->query("select dat_id from `lot_data` where dat_type={$k} and dat_expect ='{$except}' ");
		
		$countInfo = $countCheck_res->fetch(PDO::FETCH_ASSOC);
				
		
		if(!isset($countInfo['dat_id']))  //数据库中没有，说明是新数据
		{
			$insert_sql = "insert into `lot_data`(dat_type,dat_open_time,dat_expect,dat_codes) values({$k},{$open_time},'{$except}','{$codes}')";
			$insert_sql_list = "insert into `lot_data_list`(dat_type,dat_open_time,dat_expect,dat_codes) values({$k},{$open_time},'{$except}','{$codes}')";
			
			$insert_result = $db_pdo_link->exec($insert_sql);
			$insert_result = $db_pdo_link->exec($insert_sql_list);
			
			//免费参考的东西
			//saveGuess($db_pdo_link,$k,$except);   
			
			//北京快乐8转换成pc蛋蛋
			if($v=='bjkl8')
			{
				transferToPcdd($db_pdo_link,$except,$open_time,$time_detail,$codes);
			}
		}
	}
}



/**
 ** 参考计划操作
 ** added by lss@2017/07/21
 ** @param $pdo_write_read_link[object  数据库链接]
 ** @param $type [string  彩种类型]
 ** @param $except [string  开奖期数]
**/
function saveGuess($pdo_write_read_link,$type,$except)
{ 
	echo $type.','.$except;
	echo '\n';
	switch($type)
	{
		case 20:  //北京赛车
			$except_guess = intval($except) + 1;
			$val = '';
			for( $i=0; $i<=10; $i++ )
			{
				if( 0==$i )
				{
					$code_guess = getRandomCode(3,19,5);
				}else
				{
					$code_guess = getRandomCode(1,10,5);
				}
				
				$dx = rand(0,1);
				$ds = rand(0,1);
				$val .= '('.$i.',\''.$code_guess.'\','.$dx.','.$ds.',\''.$except_guess.'\'),';
			}
			$sql = 'insert into `pk10_guess`(`num`,`code`,`dx`,`ds`,`except`) VALUES '.trim($val,',');
			$guess_insert_result = $pdo_write_read_link->exec($sql);
			break;
		case 66:  //幸运飞艇  一天180期,按天算期数
			if(substr($except,-3) != 180)
			{
				$except_guess = $except + 1;
			}else
			{
				$except_guess = date("Ymd",time()).'001';
			}
			
			$val = '';
			for( $i=0; $i<=10; $i++ )
			{
				if( 0==$i )
				{
					$code_guess = getRandomCode(3,19,5);
				}else
				{
					$code_guess = getRandomCode(1,10,5);
				}
				$dx = rand(0,1);
				$ds = rand(0,1);
				$val .= '('.$i.',\''.$code_guess.'\','.$dx.','.$ds.',\''.$except_guess.'\'),';
			}
			$sql = 'insert into `mlaft_guess`(`num`,`code`,`dx`,`ds`,`except`) VALUES '.trim($val,',');
			$pdo_write_read_link->exec($sql);
			break;
		case 34:  //安微快3
			if(substr($except,-2) != 80)
			{
			   $except_guess = $except + 1;
			}else
			{
			   $except_guess = date("Ymd",strtotime("+1 day")).'001';
			}
			$val = '';
			$code_guess = getRandomCode(3,18,5);
			$dx = rand(0,1);
			$ds = rand(0,1);
			$val .= '(1,\''.$code_guess.'\','.$dx.','.$ds.',\''.$except_guess.'\'),';
			$sql = 'insert into `ahk3_guess`(`num`,`code`,`dx`,`ds`,`except`) VALUES '.trim($val,',');
			$pdo_write_read_link->exec($sql);
			break;
		case 1:  //重庆时时彩
			$exceptend = substr($except,-3);
			if( intval($exceptend) == 120 )
			{
				$except_guess = date('Ymd').'01';
			}else{
				if(intval($exceptend) >98 )
				{
					$except_guess = date('Ymd').''.(intval($exceptend)+1);
				}else
				{
					$except_guess = date('Ymd').'0'.(intval($exceptend)+1);
				}
			}
			$val = '';
			for( $i=0; $i<=5; $i++ )
			{
				if( 0==$i )
				{
					$code_guess = rand(0,1);
				}else
				{
					$code_guess = getRandomCode(1,10,5);
				}
				$dx = rand(0,1);
				$ds = rand(0,1);
				$val .= '('.$i.',\''.$code_guess.'\','.$dx.','.$ds.',\''.$except_guess.'\'),';
			}
			$sql = 'insert into `cqssc_guess`(`num`,`code`,`dx`,`ds`,`except`) VALUES '.trim($val,',');
			$pdo_write_read_link->exec($sql);
			break;
	}
}

/**
 ** 北京快乐8 转换成 pc 蛋蛋
**/
function transferToPcdd($pdo_write_read_link,$except,$open_time,$time_detail,$codes)
{
	$countCheck_res = $pdo_write_read_link->query("select dat_id from `lot_data` where dat_type='68' and dat_expect ='{$except}'");
	$countInfo = $countCheck_res->fetch(PDO::FETCH_ASSOC);
	if($countInfo)
	{
		return true;
	}
	
	$dat_codes = explode(',',$codes);
	$dat_codes = array_slice($dat_codes,0,18 );
	foreach($dat_codes as $k=>$v)
	{
		$dat_codes[$k] = ltrim($v,'0');
	}
	$code_1 = $dat_codes[0] + $dat_codes[1] + $dat_codes[2] + $dat_codes[3] + $dat_codes[4]+ $dat_codes[5];
	$code_2 = $dat_codes[6] + $dat_codes[7] + $dat_codes[8] + $dat_codes[9] + $dat_codes[10]+ $dat_codes[11];
	$code_3 = $dat_codes[12] + $dat_codes[13] + $dat_codes[14] + $dat_codes[15] + $dat_codes[16]+ $dat_codes[17];
	
	$code_1 = substr($code_1, -1);
	$code_2 = substr($code_2, -1); 
	$code_3 = substr($code_3, -1); 
	$final_codes = $code_1.','.$code_2.','.$code_3;
	
	$insert_sql = "insert into `lot_data`(dat_type,dat_open_time,dat_expect,dat_codes) values('68',{$open_time},'{$except}','{$final_codes}')";
	$insert_sql_list = "insert into `lot_data_list`(dat_type,dat_open_time,dat_expect,dat_codes) values('68',{$open_time},'{$except}','{$final_codes}')";
	$insert_result = $pdo_write_read_link->exec($insert_sql);
	$insert_result = $pdo_write_read_link->exec($insert_sql_list);
	
}

/**
 ** 定义curl封装函数
 ** @param $url
 ** @param $postParam
 ** return json
**/
function fopen_url($url, $postParam = "")
{
    $file_content = '';
    if (function_exists('curl_init')) {
        $curl_handle = curl_init();
        curl_setopt($curl_handle, CURLOPT_URL, $url); // 需要获取的URL地址
        curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2); // 在发起连接前等待的时间，如果设置为0，则无限等待。
        curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1); // 将curl_exec()获取的信息以文件流的形式返回，而不是直接输出
        curl_setopt($curl_handle, CURLOPT_FAILONERROR, 1); // 显示HTTP状态码，默认行为是忽略编号小于等于400的HTTP信息
        // 在HTTP请求中包含一个"User-Agent: "头的字符串。
        curl_setopt($curl_handle, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0');
        if ($postParam != "") {
            // 启用时会发送一个常规的POST请求，类型为：application/x-www-form-urlencoded，就像表单提交的一样。
            curl_setopt($curl_handle, CURLOPT_POST, 1); 
            // 全部数据使用HTTP协议中的"POST"操作来发送。要发送文件，在文件名前面加上@前缀并使用完整路径。这个参数可以通过urlencoded后的字符串类似'para1=val1&para2=val2&...'
            curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $postParam);
        }
        $file_content = curl_exec($curl_handle);
        if ($file_content === false) {
            echo 'Curl error: ' . curl_error($curl_handle);
            $file_content = '';
        }
        curl_close($curl_handle);
    } elseif (function_exists('file_get_contents')) {
        ini_set('user_agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0');
        $file_content = @file_get_contents($url);
    } elseif (ini_get('allow_url_fopen') && ($file = @fopen($url, 'rb'))) {
        $i = 0;
        while (!feof($file) && $i++ < 1000) {
            $file_content .= strtolower(fread($file, 4096));
        }
        fclose($file);
    } else {
        $file_content = '';
    }
    return $file_content;
}

/**
 ** added by lss@2017/07/21
 ** 获取随机数字
 ** @param [$begin string 开始数字]
 ** @param [$end string 结束数字]
 ** @param [$num string 返回几个数字]
 ** return string[以,分隔的数字]
**/
function getRandomCode($begin=1,$end=10,$num=5)
{
	$codeatt = range($begin,$end);
	shuffle($codeatt);
	$ret = array_slice($codeatt,0,$num);
	return implode(',',$ret);
}
